// 生成50个耗时任务
const longTasks = []
for (let i = 0; i < 20; i++) {
    longTasks.push(
        () => {
            return new Promise((resolve, reject) => {
                let randomTime = Math.floor(Math.random() * 3000) + 3000
                setTimeout(() => {
                    resolve(`第${i + 1}个任务， 耗时${randomTime}ms`)
                }, randomTime)
            })
        }
    )
}

function runTasks(tasks, parallelNum) { // 完成并发函数
    if (tasks === null || tasks.length === 0) return
    return new Promise((resolve, reject) => {
        let count = 0
        for (let i = 0; i < tasks.length; i++) {
            if (i < parallelNum) {
                tasks[i]().then(res => {
                    count--
                    console.log(res)
                    if (count === 0 && tasks.length === 0) {
                        resolve()
                    }
                })
            } else {
                count++
            }
        }
    })
}

runTasks(longTasks, 3).then(() => {
    console.log('所有任务执行完毕')
})
